#include "designer_actions.h"
#include "designerworkbench.h"
#include "qdesigner.h"
#include "newform.h"
#include "formwindowbase_p.h"

#include <pluginmanager_p.h>
#include <qdesigner_formbuilder_p.h>
#include <qdesigner_utils_p.h>
#include <iconloader_p.h>
#include <qsimpleresource_p.h>
#include <previewmanager_p.h>
#include <codedialog_p.h>
#include <qdesigner_formwindowmanager_p.h>
#include "qdesigner_integration_p.h"


#include <QtCore/QLibraryInfo>
#include <QtCore/QBuffer>
#include <QtCore/QPluginLoader>
#include <QtCore/qdebug.h>
#include <QtCore/QTimer>
#include <QtCore/QMetaObject>
#include <QtCore/QFileInfo>
#include <QtGui/QStatusBar>
#include <QtGui/QDesktopWidget>
#include <QtGui/QCloseEvent>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <QtXml/QDomDocument>


#include <QApplication>
#include <QFileDialog>

// sdk
#include <QtDesigner/QDesignerFormEditorInterface>
#include <QtDesigner/QDesignerFormWindowInterface>
#include <QtDesigner/QDesignerLanguageExtension>
#include <QtDesigner/QDesignerMetaDataBaseInterface>
#include <QtDesigner/QDesignerFormWindowManagerInterface>
#include <QtDesigner/QDesignerFormWindowCursorInterface>
#include <QtDesigner/QDesignerFormEditorPluginInterface>
#include <QtDesigner/QDesignerObjectInspectorInterface>
#include <QtDesigner/QExtensionManager>

using namespace qdesigner_internal;

const char *QDesignerActions::defaultToolbarPropertyName = "__qt_defaultToolBarAction";

static QAction *createSeparator(QObject *parent) {
    QAction * rc = new QAction(parent);
    rc->setSeparator(true);
    return rc;
}

static QActionGroup *createActionGroup(QObject *parent, bool exclusive = false) {
    QActionGroup * rc = new QActionGroup(parent);
    rc->setExclusive(exclusive);
    return rc;
}

// Prompt for a file and make sure an extension is added
// unless the user explicitly specifies another one.

static QString getSaveFileNameWithExtension(QWidget *parent, const QString &title, QString dir, const QString &filter, const QString &extension)
{
    const QChar dot = QLatin1Char('.');

    QString saveFile;
    while (true) {
        saveFile = QFileDialog::getSaveFileName(parent, title, dir, filter, 0, QFileDialog::DontConfirmOverwrite);
        if (saveFile.isEmpty())
            return saveFile;

        const QFileInfo fInfo(saveFile);
        if (fInfo.suffix().isEmpty() && !fInfo.fileName().endsWith(dot)) {
            saveFile += dot;
            saveFile += extension;
        }

        const QFileInfo fi(saveFile);
        if (!fi.exists())
            break;

        const QString prompt = QDesignerActions::tr("%1 already exists.\nDo you want to replace it?").arg(fi.fileName());
        if (QMessageBox::warning(parent, title, prompt, QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
            break;

        dir = saveFile;
    }
    return saveFile;
}

QDesignerActions::QDesignerActions(QObject *parent):
    QObject(parent),
    m_core(QDesignerWorkbench::instance()->core()),
    m_fileActions(createActionGroup(this)),
    m_formActions(createActionGroup(this)),
    m_editActions(createActionGroup(this)),
    m_toolActions(createActionGroup(this, true)),
    m_windowActions(createActionGroup(this)),
    m_projectActions(createActionGroup(this)),
    m_newProjectAction(new QAction(qdesigner_internal::createIconSet(QLatin1String("filenew.png")), tr("&New..."), this)),
    m_openProjectAction(new QAction(qdesigner_internal::createIconSet(QLatin1String("fileopen.png")), tr("&Open..."), this)),
    m_saveProjectAction(new QAction(qdesigner_internal::createIconSet(QLatin1String("filesave.png")), tr("&Save"), this)),
    m_designerSettingsAction(new QAction(QIcon(":/images/settings_faenza.png"),tr("&Designer settigns"), this)),
    m_newFormAction(new QAction(tr("New form"),this)),
    m_openFormAction(new QAction(tr("Open form"),this)),
    m_saveFormAction(new QAction(tr("Save form"),this)),
    m_closeFormAction(new QAction(tr("Close form"),this)),
    m_editWidgetsAction(new QAction(tr("Edit Widgets"), this)),
    m_minimizeAction(new QAction(tr("&Minimize"), this)),
    m_projectSettingsAction(new QAction(QIcon(":/images/configure.png"),tr("Settings"),this)),
    m_projectDatabaseAction(new QAction(QIcon(":/images/database.png"),tr("Database"),this)),
    m_projectScriptAction(new QAction(QIcon(":/images/javascript.png"),"Javascript",this)),
    m_runProjectAction(new QAction(QIcon(":/images/run.png"),"Run",this)),
    m_closeProjectAction(new QAction(tr("Close project"), this)),
    m_quitAction(new QAction(tr("&Quit"), this)),
    m_windowListSeparatorAction(createSeparator(this))
{
    //m_core = QDesignerWorkbench::instance()->core();
    m_workbench = QDesignerWorkbench::instance();
    Q_ASSERT(m_core != 0);
    qdesigner_internal::QDesignerFormWindowManager *ifwm = qobject_cast<qdesigner_internal::QDesignerFormWindowManager *>(m_core->formWindowManager());
    Q_ASSERT(ifwm);
    m_previewFormAction = ifwm->actionDefaultPreview();

    m_editWidgetsAction->setObjectName(QLatin1String("__qt_edit_widgets_action"));
    m_newFormAction->setObjectName(QLatin1String("__qt_new_form_action"));
    m_openFormAction->setObjectName(QLatin1String("__qt_open_form_action"));
    m_saveFormAction->setObjectName(QLatin1String("__qt_save_form_action"));
    m_previewFormAction->setObjectName(QLatin1String("__qt_preview_form_action"));
    m_minimizeAction->setObjectName(QLatin1String("__qt_minimize_action"));
    m_projectSettingsAction->setObjectName(QLatin1String("__qt_project_settings_action"));
    m_projectDatabaseAction->setObjectName(QLatin1String("__qt_project_database_action"));
    m_runProjectAction->setObjectName(QLatin1String("__qt_run_project_action"));
    m_projectScriptAction->setObjectName(QLatin1String("__qt_project_script_action"));
    m_closeProjectAction->setObjectName(QLatin1String("__qt_close_project_action"));

    m_newProjectAction->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    m_openProjectAction->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    m_saveProjectAction->setProperty(QDesignerActions::defaultToolbarPropertyName, true);


    QDesignerFormWindowManagerInterface *formWindowManager = m_core->formWindowManager();
    Q_ASSERT(formWindowManager != 0);
    //
    // file actions
    //
    m_newProjectAction->setShortcut(QKeySequence::New);
    connect(m_newProjectAction, SIGNAL(triggered()), this, SLOT(newProject()));
    m_fileActions->addAction(m_newProjectAction);

    m_openProjectAction->setShortcut(QKeySequence::Open);
    connect(m_openProjectAction, SIGNAL(triggered()), this, SLOT(openProject()));
    m_fileActions->addAction(m_openProjectAction);

    m_fileActions->addAction(createSeparator(this));

    m_saveProjectAction->setShortcut(QKeySequence::Save);
    connect(m_saveProjectAction, SIGNAL(triggered()), this, SLOT(saveProject()));
    m_fileActions->addAction(m_saveProjectAction);
    //m_saveProjectAction->setEnabled(false);

    m_fileActions->addAction(m_designerSettingsAction);
    connect(m_designerSettingsAction, SIGNAL(triggered()), this, SLOT(desingerSettings()));

    m_fileActions->addAction(createSeparator(this));

    m_fileActions->addAction(m_closeProjectAction);
    connect(m_closeProjectAction, SIGNAL(triggered()), this, SLOT(closeProject()));

    m_quitAction->setShortcuts(QKeySequence::Quit);
    m_quitAction->setMenuRole(QAction::QuitRole);
    connect(m_quitAction, SIGNAL(triggered()), this, SLOT(shutdown()));
    m_fileActions->addAction(m_quitAction);
    //
    // edit actions
    //
    QAction *undoAction = formWindowManager->actionUndo();
    undoAction->setObjectName(QLatin1String("__qt_undo_action"));
    undoAction->setShortcut(QKeySequence::Undo);
    m_editActions->addAction(undoAction);

    QAction *redoAction = formWindowManager->actionRedo();
    redoAction->setObjectName(QLatin1String("__qt_redo_action"));
    redoAction->setShortcut(QKeySequence::Redo);
    m_editActions->addAction(redoAction);

    m_editActions->addAction(createSeparator(this));

    m_editActions->addAction(formWindowManager->actionCut());
    m_editActions->addAction(formWindowManager->actionCopy());
    m_editActions->addAction(formWindowManager->actionPaste());
    m_editActions->addAction(formWindowManager->actionDelete());

    m_editActions->addAction(formWindowManager->actionSelectAll());

    m_editActions->addAction(createSeparator(this));

    m_editActions->addAction(formWindowManager->actionLower());
    m_editActions->addAction(formWindowManager->actionRaise());

    formWindowManager->actionLower()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    formWindowManager->actionRaise()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);

    //
    // edit mode actions
    //
    m_editWidgetsAction->setCheckable(true);
    QList<QKeySequence> shortcuts;
    shortcuts.append(QKeySequence(Qt::Key_F3));
    m_editWidgetsAction->setShortcuts(shortcuts);
    QIcon fallback(m_core->resourceLocation() + QLatin1String("/widgettool.png"));
    m_editWidgetsAction->setIcon(QIcon::fromTheme("designer-edit-widget", fallback));
    connect(m_editWidgetsAction, SIGNAL(triggered()), this, SLOT(editWidgetsSlot()));
    m_editWidgetsAction->setChecked(true);
    m_editWidgetsAction->setEnabled(false);
    m_editWidgetsAction->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    m_toolActions->addAction(m_editWidgetsAction);

//    connect(formWindowManager, SIGNAL(activeFormWindowChanged(QDesignerFormWindowInterface*)),
//                this, SLOT(activeFormWindowChanged(QDesignerFormWindowInterface*)));

    // TODO: Temporary commented
    QList<QObject*> builtinPlugins = QPluginLoader::staticInstances();
    builtinPlugins += m_core->pluginManager()->instances();
    foreach (QObject *plugin, builtinPlugins) {
        if (QDesignerFormEditorPluginInterface *formEditorPlugin = qobject_cast<QDesignerFormEditorPluginInterface*>(plugin)) {
            if (QAction *action = formEditorPlugin->action()) {
                //qDebug()<<action;
                m_toolActions->addAction(action);
                action->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
                action->setCheckable(true);
            }
        }
    }

    //
    // window actions
    //
    m_minimizeAction->setEnabled(false);
    m_minimizeAction->setCheckable(true);
    m_minimizeAction->setShortcut(tr("CTRL+M"));
    connect(m_minimizeAction, SIGNAL(triggered()), m_workbench, SLOT(toggleFormMinimizationState()));
    m_windowActions->addAction(m_minimizeAction);

    //
    // project actions
    //
    m_runProjectAction->setShortcut(tr("CTRL+R"));
    m_projectDatabaseAction->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    m_projectScriptAction->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    m_runProjectAction->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    m_projectActions->addAction(m_projectSettingsAction);
    m_projectActions->addAction(m_projectDatabaseAction);
    m_projectActions->addAction(m_projectScriptAction);
    m_projectActions->addAction(m_projectSettingsAction);
    m_projectActions->addAction(m_runProjectAction);
    connect(m_runProjectAction, SIGNAL(triggered()), m_workbench, SLOT(runProjectSlot()));
    connect(m_projectSettingsAction, SIGNAL(triggered()), m_workbench, SLOT(projectSettingsSlot()));
    connect(m_projectDatabaseAction, SIGNAL(triggered()), m_workbench, SLOT(projectDatabaseSlot()));
    connect(m_projectScriptAction, SIGNAL(triggered()), m_workbench, SLOT(editProjecScriptSlot()));

    //
    // form actions
    //
    connect(m_newFormAction, SIGNAL(triggered()), this, SLOT(createForm()));
    connect(m_openFormAction, SIGNAL(triggered()), this, SLOT(slotOpenForm()));
    connect(m_saveFormAction, SIGNAL(triggered()), this, SLOT(saveForm()));

    m_formActions->addAction(m_newFormAction);
    m_formActions->addAction(m_saveFormAction);
    m_formActions->addAction(m_openFormAction);

    m_formActions->addAction(createSeparator(this));
    m_formActions->addAction(formWindowManager->actionHorizontalLayout());
    m_formActions->addAction(formWindowManager->actionVerticalLayout());
    m_formActions->addAction(formWindowManager->actionSplitHorizontal());
    m_formActions->addAction(formWindowManager->actionSplitVertical());
    m_formActions->addAction(formWindowManager->actionGridLayout());
    m_formActions->addAction(formWindowManager->actionFormLayout());
    m_formActions->addAction(formWindowManager->actionBreakLayout());
    m_formActions->addAction(formWindowManager->actionAdjustSize());
    m_formActions->addAction(formWindowManager->actionSimplifyLayout());
    m_formActions->addAction(createSeparator(this));
    formWindowManager->actionHorizontalLayout()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    formWindowManager->actionVerticalLayout()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    formWindowManager->actionSplitHorizontal()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    formWindowManager->actionSplitVertical()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    formWindowManager->actionGridLayout()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    formWindowManager->actionFormLayout()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    formWindowManager->actionBreakLayout()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);
    formWindowManager->actionAdjustSize()->setProperty(QDesignerActions::defaultToolbarPropertyName, true);

    m_formActions->addAction(m_previewFormAction);

    connect(formWindowManager, SIGNAL(activeFormWindowChanged(QDesignerFormWindowInterface*)),
                this, SLOT(activeFormWindowChanged(QDesignerFormWindowInterface*)));

    projectStateChanged();
}

void QDesignerActions::activeFormWindowChanged(QDesignerFormWindowInterface *formWindow)
{
    const bool enable = formWindow != 0;
    //m_saveProjectAction->setEnabled(enable);
    m_editWidgetsAction->setEnabled(enable);
}

void QDesignerActions::projectStateChanged()
{
    bool bProject = m_workbench->project() != 0;

    m_projectActions->setEnabled(bProject);
    m_newFormAction->setEnabled(bProject);
    m_openFormAction->setEnabled(bProject);
    m_saveFormAction->setEnabled(bProject);
    m_saveProjectAction->setEnabled(bProject);
    m_closeFormAction->setEnabled(bProject);    
    m_closeProjectAction->setEnabled(bProject);
}

void QDesignerActions::saveForm()
{
    if (QDesignerFormWindowInterface *fw = m_core->formWindowManager()->activeFormWindow()) {
        if (saveForm(fw)){
            //showStatusBarMessage(savedMessage(QFileInfo(fw->fileName()).fileName()));
            qDebug()<<"TODO: implement showStatusBarMessage()";
        }
    }
}

bool QDesignerActions::saveForm(QDesignerFormWindowInterface *fw)
{
    bool ret;
    if (fw->fileName().isEmpty())
        ret = saveFormAs(fw);
    else
        ret =  writeOutForm(fw, fw->fileName());
    return ret;
}
static QString createBackup(const QString &fileName)
{
    const QString suffix = QLatin1String(".bak");
    QString backupFile = fileName + suffix;
    QFileInfo fi(backupFile);
    int i = 0;
    while (fi.exists()) {
        backupFile = fileName + suffix + QString::number(++i);
        fi.setFile(backupFile);
    }

    if (QFile::copy(fileName, backupFile))
        return backupFile;
    return QString();
}

static void removeBackup(const QString &backupFile)
{
    if (!backupFile.isEmpty())
        QFile::remove(backupFile);
}

bool QDesignerActions::writeOutForm(QDesignerFormWindowInterface *fw, const QString &saveFile)
{
    Q_ASSERT(fw && !saveFile.isEmpty());

    QString backupFile;
    QFileInfo fi(saveFile);
    if (fi.exists())
        backupFile = createBackup(saveFile);

    QString contents = fw->contents();
    if (qdesigner_internal::FormWindowBase *fwb = qobject_cast<qdesigner_internal::FormWindowBase *>(fw)) {
        if (fwb->lineTerminatorMode() == qdesigner_internal::FormWindowBase::CRLFLineTerminator)
            contents.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
    }
    const QByteArray utf8Array = contents.toUtf8();
    m_workbench->updateBackup(fw);

    QFile f(saveFile);
    while (!f.open(QFile::WriteOnly)) {
        QMessageBox box(QMessageBox::Warning,
                        tr("Save Form?"),
                        tr("Could not open file"),
                        QMessageBox::NoButton, fw);

        box.setWindowModality(Qt::WindowModal);
        box.setInformativeText(tr("The file %1 could not be opened."
                               "\nReason: %2"
                               "\nWould you like to retry or select a different file?")
                                .arg(f.fileName()).arg(f.errorString()));
        QPushButton *retryButton = box.addButton(QMessageBox::Retry);
        retryButton->setDefault(true);
        QPushButton *switchButton = box.addButton(tr("Select New File"), QMessageBox::AcceptRole);
        QPushButton *cancelButton = box.addButton(QMessageBox::Cancel);
        box.exec();

        if (box.clickedButton() == cancelButton) {
            removeBackup(backupFile);
            return false;
        } else if (box.clickedButton() == switchButton) {
            QString extension = uiExtension();
            const QString fileName = QFileDialog::getSaveFileName(fw, tr("Save Form As"),
                                                                  QDir::current().absolutePath(),
                                                                  QLatin1String("*.") + extension);
            if (fileName.isEmpty()) {
                removeBackup(backupFile);
                return false;
            }
            if (f.fileName() != fileName) {
                removeBackup(backupFile);
                fi.setFile(fileName);
                backupFile.clear();
                if (fi.exists())
                    backupFile = createBackup(fileName);
            }
            f.setFileName(fileName);
            fw->setFileName(fileName);
        }
        // loop back around...
    }
    while (f.write(utf8Array, utf8Array.size()) != utf8Array.size()) {
        QMessageBox box(QMessageBox::Warning, tr("Save Form?"),
                        tr("Could not write file"),
                        QMessageBox::Retry|QMessageBox::Cancel, fw);
        box.setWindowModality(Qt::WindowModal);
        box.setInformativeText(tr("It was not possible to write the entire file %1 to disk."
                                "\nReason:%2\nWould you like to retry?")
                                .arg(f.fileName()).arg(f.errorString()));
        box.setDefaultButton(QMessageBox::Retry);
        switch (box.exec()) {
        case QMessageBox::Retry:
            f.resize(0);
            break;
        default:
            return false;
        }
    }
    f.close();
    removeBackup(backupFile);
    //addRecentFile(saveFile);
    m_saveDirectory = QFileInfo(f).absolutePath();

    fw->setDirty(false);
    fw->parentWidget()->setWindowModified(false);
    return true;
}

#include "project.h"

void QDesignerActions::newProject()
{
    QFileDialog dlg;
    dlg.setAcceptMode(QFileDialog::AcceptSave);
    dlg.setFilter("Script project (*.sp)");    
    m_workbench->closeProject();

    if(dlg.exec() && dlg.selectedFiles().size()==1) {
        QString file = dlg.selectedFiles()[0];
        file = file.right(file.length()-file.lastIndexOf('/')-1);
        if(file.endsWith(".sp")==false)
            file+= ".sp";

        QDir dir = dlg.directory();

        m_workbench->m_project = new Project(dir.path()+"/"+file);
        m_saveProjectAction->setEnabled(true);
    }
    projectStateChanged();
}
#include "designer_settings.h"
void QDesignerActions::openProject()
{
    QFileDialog dlg;
    dlg.setAcceptMode(QFileDialog::AcceptOpen);
    dlg.setFilter("Script project (*.sp)");

    if(dlg.exec() && dlg.selectedFiles().size()==1) {
        QString fileName = dlg.selectedFiles()[0];
        m_saveProjectAction->setEnabled(true);
        if(!fileName.isEmpty())
            {
                m_workbench->openProject(fileName);
            }
        projectStateChanged();
      }
}

void QDesignerActions::closeProject()
{
    m_workbench->closeProject();
}

void QDesignerActions::saveProject()
{
    m_workbench->saveProject();
}

void QDesignerActions::shutdown()
{
    // Follow the idea from the Mac, i.e. send the Application a close event
    // and if it's accepted, quit.
    QCloseEvent ev;
    QApplication::sendEvent(qDesigner, &ev);
    if (ev.isAccepted())
        qDesigner->quit();
}

bool QDesignerActions::openForm(QWidget *parent)
{
    //closePreview();
    const QString extension = uiExtension();
    const QStringList fileNames = QFileDialog::getOpenFileNames(parent, tr("Open Form"),
        m_openDirectory, tr("Designer UI files (*.%1);;All Files (*)").arg(extension), 0, QFileDialog::DontUseSheet);

    if (fileNames.isEmpty())
        return false;

    bool atLeastOne = false;
    foreach (const QString &fileName, fileNames) {
        if (readInForm(fileName) && !atLeastOne)
            atLeastOne = true;
    }

    return atLeastOne;
}

void QDesignerActions::setWindowListSeparatorVisible(bool visible)
{
    m_windowListSeparatorAction->setVisible(visible);
}


QString QDesignerActions::uiExtension() const
{
    QDesignerLanguageExtension *lang
        = qt_extension<QDesignerLanguageExtension *>(m_core->extensionManager(), m_core);
    if (lang)
        return lang->uiExtension();
    return QLatin1String("ui");
}

bool QDesignerActions::readInForm(const QString &fileName)
{
    QString fn = fileName;

    // First make sure that we don't have this one open already.
    QDesignerFormWindowManagerInterface *formWindowManager = m_core->formWindowManager();
    const int totalWindows = formWindowManager->formWindowCount();
    for (int i = 0; i < totalWindows; ++i) {
        QDesignerFormWindowInterface *w = formWindowManager->formWindow(i);
        if (w->fileName() == fn) {
            w->raise();
            formWindowManager->setActiveFormWindow(w);
            //addRecentFile(fn);
            return true;
        }
    }

    // Otherwise load it.
    do {
        QString errorMessage;
        if (QDesignerWorkbench::instance()->openForm(fn, &errorMessage)) {
            //addRecentFile(fn);
            m_openDirectory = QFileInfo(fn).absolutePath();
            return true;
        } else {
            // prompt to reload
            QMessageBox box(QMessageBox::Warning, tr("Read error"),
                            tr("%1\nDo you want to update the file location or generate a new form?").arg(errorMessage),
                            QMessageBox::Cancel, m_core->topLevel());

            QPushButton *updateButton = box.addButton(tr("&Update"), QMessageBox::ActionRole);
            QPushButton *newButton    = box.addButton(tr("&New Form"), QMessageBox::ActionRole);
            box.exec();
            if (box.clickedButton() == box.button(QMessageBox::Cancel))
                return false;

            if (box.clickedButton() == updateButton) {
                const QString extension = uiExtension();
                fn = QFileDialog::getOpenFileName(m_core->topLevel(),
                                                  tr("Open Form"), m_openDirectory,
                                                  tr("Designer UI files (*.%1);;All Files (*)").arg(extension), 0, QFileDialog::DontUseSheet);

                if (fn.isEmpty())
                    return false;
            } else if (box.clickedButton() == newButton) {
                // If the file does not exist, but its directory, is valid, open the template with the editor file name set to it.
                // (called from command line).
                QString newFormFileName;
                const  QFileInfo fInfo(fn);
                if (!fInfo.exists()) {
                    // Normalize file name
                    const QString directory = fInfo.absolutePath();
                    if (QDir(directory).exists()) {
                        newFormFileName = directory;
                        newFormFileName  += QLatin1Char('/');
                        newFormFileName  += fInfo.fileName();
                    }
                }
                showNewFormDialog(newFormFileName);
                return false;
            }
        }
    } while (true);
    return true;
}
void QDesignerActions::editWidgetsSlot()
{
    QDesignerFormWindowManagerInterface *formWindowManager = m_core->formWindowManager();
    for (int i=0; i<formWindowManager->formWindowCount(); ++i) {
        QDesignerFormWindowInterface *formWindow = formWindowManager->formWindow(i);
        formWindow->editWidgets();
    }
}

void QDesignerActions::showNewFormDialog(const QString &fileName)
{
    //closePreview();
    NewForm *dlg = new NewForm(m_core->topLevel(), fileName);

    dlg->setAttribute(Qt::WA_DeleteOnClose);
    dlg->setAttribute(Qt::WA_ShowModal);

    dlg->setGeometry(fixDialogRect(dlg->rect()));
    dlg->exec();
}

QRect QDesignerActions::fixDialogRect(const QRect &rect) const
{
    QRect frameGeometry;
    const QRect availableGeometry = QApplication::desktop()->availableGeometry(m_core->topLevel());

    frameGeometry = m_core->topLevel()->frameGeometry();

    QRect dlgRect = rect;
    dlgRect.moveCenter(frameGeometry.center());

    // make sure that parts of the dialog are not outside of screen
    dlgRect.moveBottom(qMin(dlgRect.bottom(), availableGeometry.bottom()));
    dlgRect.moveRight(qMin(dlgRect.right(), availableGeometry.right()));
    dlgRect.moveLeft(qMax(dlgRect.left(), availableGeometry.left()));
    dlgRect.moveTop(qMax(dlgRect.top(), availableGeometry.top()));

    return dlgRect;
}
bool QDesignerActions::saveFormAs(QDesignerFormWindowInterface *fw)
{
    const QString extension = uiExtension();

    QString dir = fw->fileName();
    if (dir.isEmpty()) {
        do {
            // Build untitled name
            if (!m_saveDirectory.isEmpty()) {
                dir = m_saveDirectory;
                break;
            }
            if (!m_openDirectory.isEmpty()) {
                dir = m_openDirectory;
                break;
            }
            dir = QDir::current().absolutePath();
        } while (false);
        dir += QDir::separator();
        dir += QLatin1String("untitled.");
        dir += extension;
    }

    const  QString saveFile = getSaveFileNameWithExtension(fw, tr("Save Form As"), dir, tr("Designer UI files (*.%1);;All Files (*)").arg(extension), extension);
    if (saveFile.isEmpty())
        return false;

    fw->setFileName(saveFile);
    return writeOutForm(fw, saveFile);
}

void QDesignerActions::createForm()
{
    showNewFormDialog(QString());
}

void QDesignerActions::slotOpenForm()
{
    openForm(m_core->topLevel());
}
#include "designersettings.h"
void QDesignerActions::desingerSettings()
{
    DesignerSettings dlg;
    dlg.exec();
}


